package com.Txunda.fxw.ui.activity.other;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.tool.Toolkit;
import com.Txunda.fxw.ui.base.BaseAty;
import com.Txunda.fxw.ui.callback.InfoWindowAdapter;
import com.Txunda.fxw.ui.dialog.CustomDialog;
import com.Txunda.fxw.ui.toolkit.tool.RouteTool;
import com.Txunda.fxw.ui.toolkit.util.AMapUtil;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationClientOption.AMapLocationProtocol;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 路线图
 *
 * @author Administrator
 *
 */
public class PathAty extends BaseAty implements OnMapClickListener, OnMarkerClickListener, OnInfoWindowClickListener,
		InfoWindowAdapter, OnRouteSearchListener {

	@ViewInject(R.id.aty_title3_tv_center)
	private TextView aty_title3_tv_center;
	@ViewInject(R.id.aty_title3_tv_right2)
	private TextView aty_title3_tv_right2;
	public AMapLocationClient mLocationClient = null;
	private String com_lnt;
	private String com_lat;
	public Double longitude;
	public Double latitude;
	private Marker marker3;
	private LatLng latlng3;
	@ViewInject(R.id.map)
	private MapView mView;
	private AMap aMap;

	private Marker marker1;
	private LatLng latlng1;
	private MarkerOptions markerOption1;

	@ViewInject(R.id.linear_pop)
	private LinearLayout linear_pop;

	@ViewInject(R.id.company_img)
	private ImageView company_img;
	@ViewInject(R.id.company_name)
	private TextView company_name;
	@ViewInject(R.id.company_address)
	private TextView company_address;

	@ViewInject(R.id.path_id)
	private LinearLayout path_id;

	/// ========================
	private Context mContext;
	private RouteSearch mRouteSearch;
	private DriveRouteResult mDriveRouteResult;
	private LatLonPoint mStartPoint;
	private LatLonPoint mEndPoint;
	private final int ROUTE_TYPE_DRIVE = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mView.onCreate(savedInstanceState);
		aMap = mView.getMap();
		// 初始化
		initLocation();

		Glide.with(this).load(pic).into(company_img);
		company_name.setText(name);
		company_address.setText(address);

		searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);

	}

	private void setfromandtoMarker() {

	}

	/**
	 * 开始搜索路径规划方案
	 */
	public void searchRouteResult(int routeType, int mode) {
		if (mStartPoint == null) {
			showToast("定位中，稍后再试...");
			return;
		}
		if (mEndPoint == null) {
			showToast("终点未设置");
		}

		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);
		if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
			DriveRouteQuery query = new DriveRouteQuery(fromAndTo, mode, null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路

			mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
		}
	}

	@Override
	protected int getLayoutResId() {
		return R.layout.aty_path;
	}

	// 第一步:初始化
	private void initLocation() {
		mLocationClient = new AMapLocationClient(getApplicationContext());
		mLocationClient.setLocationOption(getDefaultOption());
		mLocationClient.setLocationListener(locationListener);

		startLocation();

	}

	@Override
	@OnClick({ R.id.path_id, R.id.map,R.id.aty_title3_tv_right2})
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
			case R.id.aty_title3_tv_right2:
				CustomDialog dialog =new CustomDialog(this);
				CustomDialog.Builder builder = new CustomDialog.Builder(this);

				builder.setTitle("提示");                    //百度地图
				builder.setPositiveButton("百度地图", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						getBaiduMap();
						dialog.dismiss();
					}
				});
				builder.setNegativeButton("高德地图",
						new android.content.DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								getGasMap();
								dialog.dismiss();
							}
						});

				builder.create().show();
				break;
			case R.id.path_id:
				if (linear_pop.getVisibility() == View.VISIBLE) {
					linear_pop.setVisibility(View.GONE);
				}
				break;

			default:
				break;
		}
	}

	//=========================================================
	private boolean isInstallByread(String packageName) {
		return new File("/data/data/" + packageName).exists();
	}

	//判断百度地图
	private void getBaiduMap() {
		//RealTimeMonitorResultModel realTimeMonitorResultModel = FindCarMapManager.getRealTimeMonitorResultModel();
		try {

			if(isInstallByread("com.baidu.BaiduMap")){

				Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:"+latitude+","+longitude+"|name:起点&destination="+lat+","+lnt+"&mode=drivingion=终点&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
				startActivity(intent); //启动调用
				Log.e("GasStation", "百度地图客户端已经安装") ;
			}else{
				showToast("请安装百度地图客户端");
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	//跳转高德地图
	private void getGasMap(){
		try {
			//启动该页面即可
			if(isInstallByread("com.autonavi.minimap")){
				// RealTimeMonitorResultModel mapFindCarResultModel = FindCarMapManager.getRealTimeMonitorResultModel();
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				//将功能Scheme以URI的方式传入data
				//当前经纬度
				//终点经纬度

				Uri uri = Uri.parse("androidamap://route?sourceApplication=amap&slat="+latitude+"&slon="+longitude+"&sname=我的位置&dlat="+lat+"&dlon="+lnt+"&dname="+address+"&dev=0&t=2");
				intent.setData(uri);
				intent.setPackage("com.autonavi.minimap");

				startActivity(intent);
				Log.e("GasStation", "高得地图客户端已经安装") ;
			}else{
				showToast("请安装高德地图客户端");
			}

		}catch (Exception e){
			e.printStackTrace();
		}
	}




	private void startLocation() {
		mLocationClient.startLocation();
	}

	private AMapLocationClientOption getDefaultOption() {
		AMapLocationClientOption mOption = new AMapLocationClientOption();
		mOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		mOption.setGpsFirst(false);
		mOption.setHttpTimeOut(30000);
		mOption.setInterval(2000);
		mOption.setNeedAddress(true);
		mOption.setOnceLocation(true);
		mOption.setOnceLocationLatest(false);
		AMapLocationClientOption.setLocationProtocol(AMapLocationProtocol.HTTP);
		return mOption;
	}

	public AMapLocationListener locationListener = new AMapLocationListener() {

		@Override
		public void onLocationChanged(AMapLocation loc) {

			if (null != loc) {

				longitude = loc.getLongitude();
				latitude = loc.getLatitude();
				latlng3 = new LatLng(latitude, longitude);

				mStartPoint = new LatLonPoint(latitude, longitude);// 起点，116.335891,39.942295
				double lat2 = Double.parseDouble(lat);
				double lnt2 = Double.parseDouble(lnt);

				mEndPoint = new LatLonPoint(lat2, lnt2);// 终点，116.481288,39.995576
				setfromandtoMarker();

				searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);

				// if (aMap == null) {
				// aMap = mView.getMap();
				// addMarkersToMap();
				//
				// }
				// 图标消失
				aMap.setOnMapClickListener(new OnMapClickListener() {

					@Override
					public void onMapClick(LatLng arg0) {
						if (linear_pop.getVisibility() == View.VISIBLE) {
							linear_pop.setVisibility(View.GONE);
						}
					}
				});

				// LatLng marker1 = new LatLng(latitude, longitude);
				// aMap.setMyLocationEnabled(false);
				// aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
				//
				// aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
				//
				// 地图上定义当前标记
				final LatLng latLng = new LatLng(latitude, longitude);

				final Marker marker = aMap.addMarker(new MarkerOptions().position(AMapUtil.convertToLatLng(mStartPoint))
						.icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));

				Marker marker2 = aMap.addMarker(new MarkerOptions().position(AMapUtil.convertToLatLng(mEndPoint))
						.icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
				// MarkerOptions markerOptions2 =new MarkerOptions();
				// aMap.addMarker(markerOptions2
				// .position(AMapUtil.convertToLatLng(mEndPoint))
				// .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));

				// 定位附近的茶馆
				// 先绘制自定义的Marker\

				// LatLng latLng2 =new LatLng(lat2,lnt2);
				// MarkerOptions markerOptions =new MarkerOptions();
				// String area =
				// PreferenceUtil.readString(getApplicationContext(),
				// PreferenceUtil.sp_mode);
				// //"39.1417730000,117.2165860000"
				// markerOptions.title(area).snippet(lat+","+lnt);
				// markerOptions.draggable(true);
				// markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),
				// R.drawable.icon_address2)));
				//
				// final Marker marker2
				// =aMap.addMarker(markerOptions.position(latLng2));

				// 定义Marker点击事件监听
				AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {

					@Override
					public boolean onMarkerClick(Marker arg0) {
						LatLng position = arg0.getPosition();
						if (position.equals(latLng)) {
							linear_pop.setVisibility(View.GONE);
						} else {
							linear_pop.setVisibility(View.VISIBLE);
						}
						// if(arg0.equals(marker)){
						//
						// return true;
						// }
						// linear_pop.setVisibility(View.VISIBLE);

						return true;
					}
				};
				aMap.setOnMarkerClickListener(markerClickListener);

			} else {
				Toast.makeText(PathAty.this, "定位失败", Toast.LENGTH_SHORT).show();
			}
		}

	};
	private String lat;
	private String lnt;
	private String name;
	private String address;
	private String pic;

	private void addMarkersToMap() {
		markerOption1 = new MarkerOptions();
		markerOption1.icon(BitmapDescriptorFactory
				.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_coffee)));

		markerOption1.position(latlng1);
		markerOption1.draggable(true);
		marker1 = aMap.addMarker(markerOption1);
		marker1.showInfoWindow();

	}

	@Override
	protected void initialized() {
		aty_title3_tv_right2.setVisibility(View.VISIBLE);
		aty_title3_tv_right2.setText("开始导航");
		lat = getIntent().getExtras().getString("lat"); // 纬度
		lnt = getIntent().getExtras().getString("lnt"); // 经度
		name = getIntent().getExtras().getString("name"); // 商家名称
		address = getIntent().getExtras().getString("address"); // 商家地址
		pic = getIntent().getExtras().getString("pic"); // 商家图片
		aty_title3_tv_center.setText("地址");

		// registerListener();
		mRouteSearch = new RouteSearch(this);
		mRouteSearch.setRouteSearchListener(this);

	}

	@Override
	protected void requestData() {

	}

	@Override
	public void onBusRouteSearched(BusRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
		aMap.clear();// 清理地图上的所有覆盖物
		if (errorCode == 1000) {
			if (result != null && result.getPaths() != null) {
				if (result.getPaths().size() > 0) {

					mDriveRouteResult = result;
					final DrivePath drivePath = mDriveRouteResult.getPaths().get(0);

//					// =======================
					List<LatLonPoint> throughPointList = new ArrayList<LatLonPoint>();
					//throughPointList.add(mStartPoint);
					//throughPointList.add(mEndPoint);
					RouteTool drivingRouteOverlay = new RouteTool(PathAty.this, aMap, drivePath, mStartPoint, mEndPoint,
							throughPointList,Color.YELLOW, Toolkit.dip2px(PathAty.this, 4));
//					drivingRouteOverlay.setView(Color.YELLOW, Toolkit.dip2px(PathAty.this, 4));

					drivingRouteOverlay.setNodeIconVisibility(false);// 设置节点marker是否显示
					drivingRouteOverlay.setIsColorfulline(true);// 是否用颜色展示交通拥堵情况，默认true
					drivingRouteOverlay.removeFromMap();
					drivingRouteOverlay.addToMap();
					drivingRouteOverlay.zoomToSpan();

//					DrivingRouteOverLay drivingRouteOverlay = new DrivingRouteOverLay(mContext, aMap, drivePath,
//							mDriveRouteResult.getStartPos(), mDriveRouteResult.getTargetPos(), null);
//					drivingRouteOverlay.setNodeIconVisibility(false);// 设置节点marker是否显示
//					drivingRouteOverlay.setIsColorfulline(true);// 是否用颜色展示交通拥堵情况，默认true
//					drivingRouteOverlay.removeFromMap();
//					drivingRouteOverlay.addToMap();
//					drivingRouteOverlay.zoomToSpan();
//					drivingRouteOverlay.setRouteWidth(3);

					int dis = (int) drivePath.getDistance();
					int dur = (int) drivePath.getDuration();
					String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";

				} else if (result != null && result.getPaths() == null) {

				}

			} else {
				showToast("查无结果");
			}
		} else {
			showToast(errorCode + "");
		}

	}

	@Override
	public void onWalkRouteSearched(WalkRouteResult arg0, int arg1) {

	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mView.onDestroy();
	}

	@Override
	public void onRideRouteSearched(RideRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public View getInfoWindow(Marker marker) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View getInfoContents(Marker marker) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub

	}

}
